package com.wei.test.config;

import com.wei.test.Constant.CachedConstant;
import com.wei.test.Util.DateTimeUtil;
import com.wei.test.Service.LogService;
import com.wei.test.Util.AppUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebFilter(urlPatterns = "/*")
@Order(1)
public class TokenFilter implements javax.servlet.Filter {
    @Autowired
    LogService logService;

    @Autowired
    AppUtil appUtil;

    @Autowired
    DateTimeUtil dateTimeUtil;

    @Value("${filterToken}")
    private boolean filterToken;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;
        String url = request.getServletPath();

        if (url.startsWith("/internal")) {
            String privateKey = request.getHeader("Authorization");
            if (!CachedConstant.internalPrivateKey.equals(privateKey)) {
                logService.error("internal key error: {}", privateKey);
                appUtil.setResponse(response, -1);
                return;
            }
        } else if (filterToken) {
            Map jwtToken = appUtil.getJwtToken(request);
            if (jwtToken == null) {
                appUtil.setResponse(response, -1);
                return;
            }

            long expiration = dateTimeUtil.timestamp((String) jwtToken.get("expiration"));
            long currenTime = dateTimeUtil.timestamp(dateTimeUtil.dateTime());

            if (expiration < currenTime) {
                logService.error("Token超时");
                appUtil.setResponse(response, -1);
                return;
            }
        }
        chain.doFilter(req, res);
    }
}
